/**
 * 
 */
package com.cctcq.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import com.cctcq.util.jdbc.JdbcUtils;



/** 
 * @ClassName: DaoTemplate 
 * @Description: TODO(DAO操作的模板类) 
 * @author xiaohu.ma
 * @date 2012-7-12 下午02:06:27 
 *  
 */

public class DaoTemplate {
	/**
	 * @Title: find 
	 * @Description: TODO(查询单条记录对象) 
	 * @param @param sql
	 * @param @param args
	 * @param @param rowMapper
	 * @param @throws DaoException    设定文件 
	 * @return Object    返回类型(单个对象) 
	 * @throws
	 */
	public Object find(String sql, Object[] args, RowMapper rowMapper) throws DaoException {
		Connection conn = null;
		PreparedStatement ps = null;
		ResultSet rs = null;
		try {
			conn = JdbcUtils.getConnection();
			ps = conn.prepareStatement(sql);
			for (int i = 0; i < args.length; i++) {
				ps.setObject(i + 1, args[i]);
			}
			rs = ps.executeQuery();
			Object object = null;
			if (rs.next()) {
				object = rowMapper.mapRow(rs);
			}
			return object;
		} catch (SQLException e) {
			throw new DaoException(e.getMessage(), e);
		} finally {
			JdbcUtils.free(rs, ps, conn);
		}
	}
	
	/**
	 * @Title: findAll
	 * @Description: TODO(查询多条记录对象 ) 
	 * @param @param sql
	 * @param @param args
	 * @param @param rowMapper
	 * @param @return    设定文件 
	 * @return List<Object>    返回类型(多个对象)
	 * @throws
	 */
	public List<Object> findAll(String sql, Object[] args, RowMapper rowMapper) {
		Connection conn = null;
		PreparedStatement ps = null;
		ResultSet rs = null;
		List<Object> results = new ArrayList<Object>();
		try {
			conn = JdbcUtils.getConnection();
			ps = conn.prepareStatement(sql);
			for (int i = 0; i < args.length; i++)
				ps.setObject(i + 1, args[i]);
			rs = ps.executeQuery();
			Object object = null;
			while (rs.next()) {
				object = rowMapper.mapRow(rs);
				results.add(object);
			}
			return results;
		} catch (SQLException e) {
			throw new DaoException(e.getMessage(), e);
		} finally {
			JdbcUtils.free(rs, ps, conn);
		}
	}

	/**
	 * @Title: update 
	 * @Description: TODO(更新操作) 
	 * @param @param sql
	 * @param @param args
	 * @param @return    设定文件 
	 * @return int    返回类型 
	 * @throws
	 */
	public int update(String sql, Object[] args) {
		Connection conn = null;
		PreparedStatement ps = null;
		ResultSet rs = null;
		try {
			conn = JdbcUtils.getConnection();
			ps = conn.prepareStatement(sql);
			for (int i = 0; i < args.length; i++) {
				ps.setObject(i + 1, args[i]);
			}
			return ps.executeUpdate();
		} catch (SQLException e) {
			throw new DaoException(e.getMessage(), e);
		} finally {
			JdbcUtils.free(rs, ps, conn);
		}
	}
}
